import {
  createRequest,
  type RequestConfig,
  type ResponseData,
  type RequestFetchError,
} from "@/lib/request";
import { createEmitter } from "@/components/emitter";

export interface ApiResponse<T = any> {
  success: boolean;
  query: {
    count: number;
    results: Array<T>;
    limit: number;
    offset: number;
    page: number;
  };
  object: T;
  message: string;
  errors: {
    [propName: string]: Array<string>;
  };
}

export interface PaginationParams {
  page: number;
  pageSize: number;
}

export const httpEvent = createEmitter<{
  request: RequestInit;
  response: ResponseData;
  error: RequestFetchError;
}>();

export const request = createRequest({
  baseUrl: import.meta.env.VITE_BASE_URL,
  onRequest(config) {
    const info = sessionStorage.getItem("user");
    if (info) {
      config.headers = {
        ...config.headers,
        Authorization: `Bearer ${JSON.parse(info).token}`,
      };
    }
    httpEvent.emit("request", config);
  },
  onResponse(response) {
    httpEvent.emit("response", response);
  },
  onError(error) {
    httpEvent.emit("error", error);
  },
});

export const fetchApi = <T = any>(url: string, config?: RequestConfig) =>
  request<ApiResponse<T>>(url, config);
